<?php
define('START', true);

session_start();

$abs_root = '../';
$root = './';
include($abs_root . 'src/DBHandle.php');
include($abs_root . 'src/AgentHandle.php');

if(trim($_POST['username']) != ''){	
	if(trim($_POST['password']) != ''){
		$username = trim($_POST['username']);
		$password = md5(trim($_POST['password']));	
			
		$db = new DBHandle();
		
		// query database //
		$statement = "SELECT agent_id, agent_username, agent_password, agent_permissions FROM agents WHERE agent_username = '" . $username . "'";
		if(!$query = mysql_query($statement, $db->DB_HANDLE)){
			die('Unable to query database\'s table: \'agents\''); // remove when site is to be deployed
		}
		if(!mysql_num_rows($query)){
			// no such user, return a value //
			$_SESSION['loginError'] = 'No such username exist.';	
			header('refresh: 0; url=' . $abs_root . 'index.php');					
		}
		else{			
			$result = mysql_fetch_array($query); // only one entry is expected for all username are unique //			//die ("password$password <br> resultord{$result['agent_password']}");
			if(strcmp($password, $result['agent_password']) == 0){
				// set session needed variables //	strcmp($password, $result['agent_password']) == 0
					
					$_SESSION['logged'] = true;		
					$_SESSION['agentId'] = $result['agent_id'];
					$_SESSION['agentUsername'] =  $result['agent_username'];
					$_SESSION['agentPermissions'] = $result['agent_permissions'];
					$_SESSION['timeId'] = AgentHandle::agentLogIn($result['agent_id']);																	
					$_SESSION['initialized'] = true;
					$logStamp = true;	
					header('refresh: 0; url=' . $abs_root . 'index.php');														
			}																								
			else{
				// wrong password, return a value //
				//die( "password$password <br> result{$result['agent_password']}");
				$log_stamp = false;		
				$_SESSION['loginError'] = 'Wrong password.';
				header('refresh: 0; url=' . $abs_root . 'index.php');
			}	
		}

		$db->closeDBConnection();
	}
	else{
		// blank password field //
		$_SESSION['loginError'] = 'No password is entered.';
		header('refresh: 0; url=' . $abs_root . 'index.php');
	}
}
else{
	// blank username field //
	$_SESSION['loginError'] = 'No username is entered.';
	header('refresh: 0; url=' . $abs_root . 'index.php');		
}
?>
